
package tema6;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name="CargarAtributosInicioServlet", urlPatterns={"/tema6/cargarAtributosInicio"},
    initParams={@WebInitParam(name="ficheroParametrosContexto",value="/tema6/parametrosContexto.prop")})
public class CargarAtributosInicioServlet extends HttpServlet{
    
    @Override
    public void init(ServletConfig config){
        
        String nombreFicheroConfiguracion = config.getInitParameter("ficheroParametrosContexto");
        ServletContext contexto = config.getServletContext();
        InputStream is = contexto.getResourceAsStream(nombreFicheroConfiguracion);
        Properties ficheroConfiguracion = new Properties();
        try {
            ficheroConfiguracion.load(is);
            Enumeration parametros = ficheroConfiguracion.keys();
            while(parametros.hasMoreElements()){
                String atributo = (String) parametros.nextElement();
                String valor = ficheroConfiguracion.getProperty(atributo);
                contexto.setAttribute(atributo, valor);
            }
        } catch (IOException ex) {
                Logger.getLogger(CargarAtributosInicioServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    protected void procesaPeticion(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                
        ServletContext contexto = request.getServletContext();
        HttpSession sesion = request.getSession();
        Enumeration<String> cabecerasAtributos = contexto.getAttributeNames();
        while(cabecerasAtributos.hasMoreElements()){
            String atributo = cabecerasAtributos.nextElement();
            sesion.setAttribute(atributo, contexto.getAttribute(atributo).toString());                        
        }
        RequestDispatcher listaAtributosServlet = contexto.getNamedDispatcher("ListaAtributosServlet");
        listaAtributosServlet.forward(request,response);
    }   
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        procesaPeticion(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        procesaPeticion(request, response);
    }
    
}
